<template>
    <div>
        <vxe-toolbar>
            <template #buttons>
                <div class="toolbar-buttons">
                    <el-button @click="openNewProfessionDialog" @ProfessionCreated="fetchProfessions">新增专业</el-button>
                    <el-input v-model="searchQuery" style="width: 300px;" placeholder="输入名称搜索"
                        @change="filterProfessions" />
                    <el-button @click="fetchProfessions">查询</el-button>
                </div>
            </template>
        </vxe-toolbar>

        <vxe-grid border show-header :data="filteredProfessions" :columns="columns" @cell-edit-change="editProfession"
            :edit-config="{ trigger: 'dblclick', mode: 'cell' }" @edit-closed="saveData">
            <template #action="{ row }">
                <el-button link type="primary" @click="deleteProfession(row.id)">删除</el-button>
                <el-button link type="primary" @click="openModifyProfessionDialog(row)">编辑</el-button>
            </template>
        </vxe-grid>
        <NewProfessionDialog ref="newProfessionDialog" @ProfessionCreated="fetchProfessions" />
        <ModifyProfessionDialog ref="modifyProfessionDialog" @ProfessionModified="fetchProfessions" />
    </div>
</template>

<script setup>
import { deleteProfessionById, getAllProfessions } from '@/alova/api';
import ModifyProfessionDialog from '@/components/ModifyProfessionDialog.vue';
import NewProfessionDialog from '@/components/NewProfessionDialog.vue';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { ref } from 'vue';

const searchQuery = ref('');
const loading = ref(false);
const dialogVisible = ref(false); // 控制弹窗显示
const editForm = ref({}); // 存储正在编辑的数据
const modifyProfessionDialog = ref(null);
const newProfessionDialog = ref(null);

// 专家数据列表
const professionList = ref([]);

// 表格列定义
const columns = ref([
    { field: 'id', title: '序号', width: 80, editRender: { name: 'input' } },
    { field: 'name', title: '项目名称', editor: { type: 'text' }, editRender: { name: 'input' } },
    { title: '操作', field: 'action', slots: { default: 'action' }, width: 120 }
]);

const filteredProfessions = ref([...professionList.value]);

const openModifyProfessionDialog = (row) => {
    modifyProfessionDialog.value.openDialog(row);
};

const openNewProfessionDialog = () => {
    newProfessionDialog.value.openDialog();
};

const fetchProfessions = async () => {
    loading.value = true; // 开始加载
    const loader = ElLoading.service({
        fullscreen: true,
        text: "数据加载中...",
    });
    getAllProfessions().then(data => {
        loading.value = false;
        professionList.value = data;
        filteredProfessions.value = [...professionList.value];
    }).catch(error => {
        console.error("查询专业失败:", error);
    }).finally(() => {
        loading.value = false; // 结束加载
        loader.close(); // 关闭加载动画
    });
}

fetchProfessions();

// 打开弹窗进行编辑
const openEditDialog = (row) => {
    editForm.value = { ...row }; // 复制数据，防止直接修改表格数据
    dialogVisible.value = true;
};

// 保存编辑数据
const saveProfession = () => {
    const index = professionList.value.findIndex(e => e.id === editForm.value.id);
    if (index !== -1) {
        professionList.value[index] = { ...editForm.value };
    }
    dialogVisible.value = false;
};

const saveData = ({ row, field }) => {
    console.log(`字段 ${field} 修改为：`, row[field]);
    // 这里可以调用后端 API 进行数据保存
};

const editProfession = ({ row, field, value }) => {
    row[field] = value;
};

const deleteProfession = (id) => {
    ElMessageBox.confirm(
        '此操作将永久删除该专业，是否继续？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        deleteProfessionById(id).then(() => {
            ElMessage.success('删除成功！');
            professionList.value = professionList.value.filter(Profession => Profession.id !== id);
            filteredProfessions.value = [...professionList.value];
        }).catch(error => {
            console.log("删除失败:", error);
        }).finally(() => {
            console.log("finally");
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

const filterProfessions = () => {
    if (!searchQuery.value) {
        filteredProfessions.value = [...professionList.value];
    } else {
        filteredProfessions.value = professionList.value.filter(profession =>
        profession.name.includes(searchQuery.value)
        );
    }
};
</script>

<style scoped>
.toolbar-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>